import {Component} from '@angular/core';
import {App, IonicPage, NavController} from 'ionic-angular';
import {PublicService} from "../../common/public.service";
import {HttpService} from "../../providers/HttpService";
import {MATERIAL_CONMX_URL, MATERIAL_LIST_BY_GROUP_URL} from "../../providers/Constants";

/**
 *
 * 产量及耗用量录入
 */

@IonicPage()
@Component({
  selector: 'page-manage',
  templateUrl: 'manage.html',
})
export class ManagePage {

  bzDate: string;//班组日期
  bzSelect: string;//班组选择
  workProcedureName: string;
  workProcedure: string;

  //扫描后把数据保存在这里
  public dataList: Array<Object> = [];

  //用户名
  personName: string = localStorage.getItem("mpower-personName");

  constructor(public navCtrl: NavController,
              public pub: PublicService,
              public app:App,
              public http: HttpService) {
  }

  ionViewDidLoad() {
  }

  ionViewWillEnter() {
    this.bzDate = sessionStorage.getItem("setWorkTime");
    this.bzSelect = sessionStorage.getItem("setBzSelect");
    this.workProcedureName = sessionStorage.getItem("workProcedureName");
    this.workProcedure = sessionStorage.getItem("workProcedure");
    this.initList();
  }

  //动态列
  codeNameMap: Array<Object> = [];

  /**
   * 查询列表
   */
  initList() {
    this.dataList = [];
    let params = {
      sessionId: sessionStorage.getItem("session"),
      groupId: localStorage.getItem("groupId"),
      procedureId: sessionStorage.getItem("workProcedure")
    };
    this.http.get(SERVER_URL + MATERIAL_LIST_BY_GROUP_URL, '&', params, false).then(res => {
      if (res.success) {
        if (res.data.codeNameMap && res.data.codeNameMap.length > 0) {
          this.codeNameMap = res.data.codeNameMap;
        }
        if (res.data.materials) {
          for (let i = 0; i < res.data.materials.length; i++) {
            let data = res.data.materials[i];
            var obj = {
              material_code: data.material_code,//编号
              material_name: data.material_name,//名称
              material_id: data.material_id,//id
              material_unit: data.material_unit,//单位
              id: data.id,
              material_unit_t: data.material_unit_t,//单位
            };
            if (res.data.codeNameMap && res.data.codeNameMap.length > 0) {
              //防止引用赋值
              let o = JSON.parse(JSON.stringify(res.data.codeNameMap));
              for (let t = 0; t < o.length; t++) {
                let key = o[t]['code'];
                o[t]["val"] = data[key];
              }
              obj["codeNameMap"] = o;
            }
            this.dataList.push(obj);
          }
        }
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }


  public subDataList: Array<Object> = [];

  /**
   * 监听产量列变化
   * @param id
   * @param materialCode
   * @param hcode
   */
  inputChange(id: string, materialCode: string, hcode: string) {
    var val = document.getElementById(materialCode + hcode + "Con")["value"];
    this.subDataList = sessionStorage.getItem("cl_subDataList") ? JSON.parse(sessionStorage.getItem("cl_subDataList")) : [];
    let haved = true;
    if (this.subDataList && this.subDataList.length > 0) {
      let flag = false;
      for (let i = 0; i < this.subDataList.length; i++) {
        if (flag) {
          break;
        }
        if (id == this.subDataList[i]["id"] && materialCode == this.subDataList[i]["materialCode"]) {
          if (this.subDataList[i]["useMxAry"].length > 0) {
            for (let t = 0; t < this.subDataList[i]["useMxAry"].length; t++) {
              if (this.subDataList[i]["useMxAry"][t]["code"] == hcode) {
                this.subDataList[i]["useMxAry"][t]["value"] = val;
                flag = true;
                break;
              } else if (t == this.subDataList[i]["useMxAry"].length - 1) {
                this.subDataList[i]["useMxAry"].push({code: hcode, value: val});
                break;
              }
            }
          } else {
            this.subDataList[i]["useMxAry"].push({code: hcode, value: val});
            break;
          }
        } else if (i == this.subDataList.length - 1) {
          haved = false;
          break;
        }
      }
    } else {
      haved = false;
    }
    if (!haved) {
      let obj = {
        id: id,
        materialCode: materialCode,
        useMxAry: [{code: hcode, value: val}]
      };
      this.subDataList.push(obj);
    }
    sessionStorage.setItem("cl_subDataList", JSON.stringify(this.subDataList));
  }

  /**
   * 保存数据
   */
  submitBtn() {
    let conmxJson=sessionStorage.getItem("cl_subDataList");
    if(!conmxJson){
      this.pub.presentLoadingToast("当前数据未改动，不能提交！");
      return false;
    }
    let params = {
      sessionId: sessionStorage.getItem("session"),
      groupId: localStorage.getItem("groupId"),
      procedureId: sessionStorage.getItem("workProcedure"),
      conmxJson: sessionStorage.getItem("cl_subDataList")
    };
    this.http.post(SERVER_URL + MATERIAL_CONMX_URL, '&', params, false).then(res => {
      if (res.success) {
        sessionStorage.removeItem("cl_subDataList");
        this.initList();
        this.pub.presentLoadingToast("提交成功");
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  /**
   * 清空
   * 清空当前页面input值，不提交
   */
  resetBtn() {
    this.pub.presentCustomConfirm("确定清空耗用量数据吗？", "取消", "确定").then(() => {
      sessionStorage.removeItem("cl_subDataList");
      let inputs = document.getElementsByTagName("input");
      if (inputs && inputs.length > 0) {
        for (let i = 0; i < inputs.length; i++) {
          inputs[i]["value"] = "";
        }
      }
    }).catch(() => {
      return;
    });
  }
}
